package LogicSide;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.xeustechnologies.jtar.TarInputStream;

public class Uncompress {

	public static TarInputStream compressed_to_file(String input_str)
			throws FileNotFoundException, IOException, ArchiveException {

		File f = unBz2(new File(input_str));
		return unTar(f);
	}

	/**
	 * Untar an input file into an output file.
	 * 
	 * The output file is created in the output folder, having the same name as
	 * the input file, minus the '.tar' extension.
	 * 
	 * @param inputFile
	 *            the input .tar file
	 * @param outputDir
	 *            the output directory file.
	 * @throws IOException
	 */

	private static TarInputStream unTar(File inputFile)
			throws IOException {

		// Create a TarInputStream
		TarInputStream tis = new TarInputStream(new BufferedInputStream(
				new FileInputStream(inputFile)));
		return tis;

	}

	/**
	 * unBz2 an input file into an output file.
	 * 
	 * The output file is created in the output folder, having the same name as
	 * the input file, minus the '.bz2' extension.
	 * 
	 * @param inputFile
	 *            the input .bz2 file
	 * @throws IOException
	 * @throws FileNotFoundException
	 * 
	 * @return The {@File} with the unbz2ed content.
	 */
	private static File unBz2(File inputFile) throws FileNotFoundException,
			IOException {
		File outputFile = new File(inputFile.getName().substring(0,
				inputFile.getName().length() - 4));

		FileInputStream fin = new FileInputStream(inputFile);
		BufferedInputStream in = new BufferedInputStream(fin);
		FileOutputStream out = new FileOutputStream(outputFile);
		BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
		final byte[] buffer = new byte[256];
		int n = 0;
		while (-1 != (n = bzIn.read(buffer))) {
			out.write(buffer, 0, n);
		}
		out.close();
		bzIn.close();
		return outputFile;
	}
}
